package com.example.agriapp.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.agriapp.R;
import com.example.agriapp.model.bean.Article;
import com.example.agriapp.view.activity.ArticleDetailActivity;

import java.util.List;

public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.ArticleViewHolder> {

    private List<Article> articleList;
    private Context context;

    public ArticleAdapter(List<Article> articleList, Context context) {
        this.articleList = articleList;
        this.context = context;
    }


    @Override
    public ArticleViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_article, parent, false);
        return new ArticleViewHolder(view);
    }

    @Override
    public void onBindViewHolder( ArticleViewHolder holder, int position) {
        Article article = articleList.get(position);
        
        holder.titleTextView.setText(article.getTitle());
        holder.timeTextView.setText(article.getPublishTime());
        
        // 加载图片
        Glide.with(context)
                .load(article.getImageUrl())
                .into(holder.imageView);
        
        // 点击事件
        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(context, ArticleDetailActivity.class);
            intent.putExtra("article", article);
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return articleList.size();
    }

    static class ArticleViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView titleTextView;
        TextView timeTextView;

        public ArticleViewHolder( View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.article_image);
            titleTextView = itemView.findViewById(R.id.article_title);
            timeTextView = itemView.findViewById(R.id.article_time);
        }
    }
}